from django.http import Http404, HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView

import logging

from jobs.models import Job, Resume
from jobs.models import Cities, JobTypes
import html

logger = logging.getLogger(__name__)


# Create your views here.
def joblist(request):
    job_list = Job.objects.order_by('job_type')
    context = {'job_list': job_list}
    for job in job_list:
        job.city_name = Cities[job.job_city][1]
        job.type_name = JobTypes[job.job_type][1]
    return render(request, 'joblist.html', context)


def detail(request, job_id):
    try:
        job = Job.objects.get(pk=job_id)
        job.city_name = Cities[job.job_city][1]
        logger.info('job info fetch from database jobid:%s' % job_id)
    except Job.DoesNotExist:
        raise Http404("Job does not exist")
    return render(request, 'job.html', {'job': job})


class ResumeDetailView(DetailView):
    """ 简历详情页 """
    model = Resume
    template_name = 'resume_detail.html'
    # success_url = '/joblist/'


from django.contrib.auth.decorators import permission_required, login_required
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import Group, User
from django.contrib import messages

# 不处理csrf攻击
# @csrf_exempt
# 需要有添加用户的权限，只有超级管理员才能进入到这个页面
@permission_required('auth.add_user')
def create_hr_user(request):
    """ 创建 HR 用户 """
    if request.method == 'GET':
        return render(request, 'create_hr.html', {})
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        hr_group = Group.objects.get(name='hr')
        user = User(is_superuser=False, username=username, is_active=True, is_staff=True)
        user.set_password(password)
        user.save()
        user.groups.add(hr_group)
        messages.add_message(request, messages.INFO, 'user created %s' % username)
        return render(request, 'create_hr.html', {})
    return render(request, 'create_hr.html', {})


"""
    直接返回 HTML 内容的视图（这段代码返回的页面有 XSS 漏洞，能够被攻击者利用）
"""
def detail_resume(request, resume_id):
    try:
        resume = Resume.objects.get(pk=resume_id)
        # 简历人名称，简历介绍
        content = "name: %s <br> introduction: %s <br>" % (resume.username, resume.candidate_introduction)
        # 问题：能够被攻击的写法
        # return HttpResponse(content)
        # 方案一：不能被攻击的写法（不建议）
        return HttpResponse(html.escape(content))
        # 推荐方式是用render函数
    except Resume.DoesNotExist:
        raise Http404("Resume does not exist")


class ResumeCreateView(LoginRequiredMixin, CreateView):
    """    简历职位页面  """
    template_name = 'resume_form.html'
    success_url = '/joblist/'
    model = Resume
    fields = ["username", "city", "phone",
        "email", "apply_position", "gender",
        "bachelor_school", "master_school", "major", "degree", "picture", "attachment",
        "candidate_introduction", "work_experience", "project_experience"]

    # 从 URL 请求参数带入默认值
    def get_initial(self):
        initial = {}
        for x in self.request.GET:
            initial[x] = self.request.GET[x]
        return initial

    # 简历跟当前用户关联
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.applicant = self.request.user
        self.object.save()

        return HttpResponseRedirect(self.get_success_url())


